<template>
  <van-popup v-model="isShow" round position="bottom" @close="closePop">
    <div class="recording_pop">
      <div class="time">{{ duration }}</div>
      <div class="no_start">未开始录音</div>
      <div class="img_box">
        <img
          src="@/assets/images/function/recording_close.png"
          class="img_01"
          @click="closePop"
        />
        <img
          src="@/assets/images/function/recording_play.png"
          class="img_02"
          @click="toPlay(2)"
          v-if="isRecording"
        />
        <img
          src="@/assets/images/function/recording_pause.png"
          class="img_02"
          @click="toPlay(1)"
          v-else
        />
        <img
          src="@/assets/images/function/recording_check.png"
          class="img_01"
          @click="uploadRecording"
        />
      </div>
      <!-- <img
          :src="isRecording ? '@/assets/images/function/recording_play.png' : '@/assets/images/function/recording_pause.png'"
          class="img_02" @click="toPlay(isRecording ? 2 : 1)" /> -->
      <div class="start">{{ isRecording ? "停止录音" : "开始录音" }}</div>
    </div>
  </van-popup>
</template>

<script>
import { Buffer } from "buffer";
window.Buffer = window.Buffer || Buffer;
import {
  uploadMp3,
  getUploadId,
  getUploadChunk,
} from "@/api/funcation/wisdomTree";
export default {
  data() {
    return {
      isShow: true,
      mediaRecorder: null,
      audioChunks: [],
      isRecording: false,
      startTime: 0,
      timer: null,
      duration: "00:00:00",
      audioBlob: null,
      slicedAudio: null,
    };
  },
  methods: {
    //上传录音
    async uploadRecording() {
      if (!this.audioBlob) {
        return this.$toast.fail("请先录音");
      }
      let res = await uploadMp3({ file: this.audioBlob });
      if (res.code == 200) {
        this.$emit("getMp3Info", res.data);
        this.$emit("closeRecordingPop", res.data);
        return;
        this.mp3Url = res.data;
      }
    },
    // 开始录音
    async toPlay(type) {
      if (type === 1) {
        try {
          // 获取麦克风权限
          const stream = await navigator.mediaDevices.getUserMedia({
            audio: true,
          });

          // 创建 MediaRecorder 实例
          this.mediaRecorder = new MediaRecorder(stream);
          this.audioChunks = [];

          // 监听录音数据
          this.mediaRecorder.ondataavailable = (event) => {
            if (event.data.size > 0) {
              this.audioChunks.push(event.data);
            }
          };

          // 开始录音
          this.mediaRecorder.start();
          this.isRecording = true;
          this.startTime = Date.now();
          this.startTimer();

          // 更新UI
          this.$el.querySelector(".no_start").textContent = "正在录音...";
          this.$el.querySelector(".start").textContent = "停止录音";
        } catch (error) {
          this.$toast("无法访问麦克风");
        }
      } else {
        // 停止录音
        if (this.mediaRecorder && this.isRecording) {
          this.mediaRecorder.stop();
          this.isRecording = false;
          this.stopTimer();
          // 更新UI
          this.$el.querySelector(".no_start").textContent = "录音完成";
          this.$el.querySelector(".start").textContent = "开始录音";
          // 处理录音数据
          this.mediaRecorder.onstop = () => {
            this.audioBlob = new Blob(this.audioChunks, { type: "audio/mp3" });
            // 切片处理，每个切片大小为 1MB
            const chunkSize = 1024 * 1024;
            const audioChunks = [];
            let offset = 0;
            while (offset < this.audioBlob.size) {
              audioChunks.push(
                this.audioBlob.slice(offset, offset + chunkSize)
              );
              offset += chunkSize;
            }
            this.slicedAudio = audioChunks;
          };
        }
      }
    },

    // 开始计时器
    startTimer() {
      this.timer = setInterval(() => {
        const elapsed = Date.now() - this.startTime;
        this.duration = this.formatTime(elapsed);
        this.$el.querySelector(".time").textContent = this.duration;
      }, 1000);
    },

    // 停止计时器
    stopTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },

    // 格式化时间
    formatTime(ms) {
      const totalSeconds = Math.floor(ms / 1000);
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;

      return `${hours.toString().padStart(2, "0")}:${minutes
        .toString()
        .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    },

    // 关闭弹窗
    closePop() {
      if (this.isRecording) {
        this.toPlay(2); // 如果正在录音，先停止录音
      }
      this.stopTimer();
      this.duration = "00:00:00";
      this.$emit("closeRecordingPop");
    },
  },
  beforeDestroy() {
    // 组件销毁前清理资源
    this.stopTimer();
    if (this.mediaRecorder && this.isRecording) {
      this.mediaRecorder.stop();
    }
  },
};
</script>

<style lang="less" scoped>
.recording_pop {
  padding: 65px 20px 35px 20px;
  text-align: center;
  color: #333;

  .time {
    font-size: 24px;
    margin-bottom: 10px;
    font-weight: bold;
  }

  .no_start {
    color: #999;
    margin-bottom: 20px;
    font-size: 14px;
    margin: 45px 0;
  }

  .recording_img {
    width: 60px;
    height: 60px;
    margin-bottom: 10px;
    cursor: pointer;
  }

  .start {
    color: #333333;
    margin-top: 10px;
    font-size: 14px;
  }

  .img_box {
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      margin-right: 50px;

      &:last-child {
        margin: 0;
      }
    }
  }

  .img_01 {
    width: 50px;
    height: 50px;
  }

  .img_02 {
    width: 66.67px;
    height: 66.67px;
  }
}
</style>
